from inspect import isgenerator, isasyncgen
from typing import Union, Generator, AsyncGenerator

from bald_spider import Request, Item, Response
from bald_spider.exceptions import TransFormTypeError

T = Union[Request, Item]

SpiderOutputType = Union[Generator[T, None, None], AsyncGenerator[T, None]]


async def transform(func_result, response: Response):
    def set_request(t: T):
        if isinstance(t, Request):
            t.meta['depth'] = response.meta['depth']
            return t

    if isgenerator(func_result):
        for r in func_result:
            yield set_request(r)
    elif isasyncgen(func_result):
        async for r in func_result:
            yield set_request(r)
    else:
        raise TransFormTypeError('callback result must be generator or async generator ')
